# !/usr/bin/python
# -*- coding: utf-8 -*-
from conf.config import firingMsg,resolveMsg,phonenums
from util.log_util import get_logger
from util.time_util import utc_to_local
import uuid
import json
logger = get_logger()


def parseAlertManagerMsg(datas):
    if not isinstance(datas, dict):
        logger.error("request params must be dict, not {0}".format(type(datas)))
        return None
    else:
        message_list = []
        logger.info(json.dumps(datas,indent=4))
        for info in datas.get("alerts"):
            if info["status"] == "firing":
                start_time = utc_to_local(info.get("startsAt", None))
                content =  firingMsg.format(alertname=info["labels"].get("alertname", None),
                                            summary=info["annotations"].get("summary", None),
                                            status=info["labels"].get("severity", None),
                                            hosts=info["labels"].get("hosts", None),
                                            instance=info["labels"].get("instance", None),
                                            startsAt=start_time,
                                            app=info["labels"].get("app", None),
                                            description=info["annotations"].get("description", None))
            else:
                start_time = utc_to_local(info.get("startsAt", None))
                end_time = utc_to_local(info.get("endsAt", None))
                content = resolveMsg.format(alertname=info["labels"].get("alertname", None),
                                            summary=info["annotations"].get("summary", None),
                                            hosts=info["labels"].get("hosts", None),
                                            instance=info["labels"].get("instance", None),
                                            startsAt=start_time,
                                            endsAt=end_time,
                                            app=info["labels"].get("app", None))
            for i in range(0, len(phonenums)):
                message = {
                    "messageId": str(uuid.uuid4()).replace("-", ""),
                    "phoneNumber": phonenums[i],
                    "content": content
                }
                message_list.append(message)
        return message_list